package com.codes.controller;

import com.codes.core.common.result.Result;
import com.codes.service.ProductSV;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Date 2020/5/28 17:06
 * @Created by peanut
 */
@RestController
@RequestMapping("/product")
@Api(tags = "构建模块接口")
public class ProductCtr {


    @Autowired
    private ProductSV productSV;

    @ApiOperation("获取所有构件信息")
    @GetMapping("/list")
    public Result getAllProduct(@RequestParam Map<String,Object> map){

        List products = productSV.getAllProduct(  map);

        return Result.success(products);

    }

    @GetMapping("/page")
    @ApiOperation(("构件列表分页"))
    public Result productPage(@RequestParam( defaultValue="1",required=true) int   page,
                              @RequestParam( defaultValue="10",required=true) Integer limit,
                              @RequestParam Map<String,Object> map) {

        PageHelper.startPage(page,limit);
        // Map<String, Object> map =  new HashMap<>();
        List<Map<String, Object>> users = productSV.getAllProduct(  map);
        PageInfo<Map<String, Object>> info = new PageInfo< >(users);
        return Result.pages(info.getList(),(int)info.getTotal());

    }

    @ApiOperation("添加构件")
    @PostMapping("/save")
    public Result saveProduct(@RequestParam Map<String,Object> map){

        Integer productId = MapUtils.getInteger(map,"productId");
        List<Map<String,Object>>  list = productSV.getAllProduct(map);
        int re = 0;
        if(null != productId){ // 表示修改
            if(list.size()>0){

                Integer searchId = MapUtils.getInteger(list.get(0),"id");
                if(productId != searchId) return Result.failed("构件名称已经存在");
            }
            re = productSV.updateByPrimaryKeySelective(map);
        }else {
            // 名字不能重复
            if(list.size()>0) return Result.failed("构件名称已经存在");
            re = productSV.insertMap(map);
        }

        return  Result.success("操作成功",re);

    }

    @ApiOperation("删除构件")
    @PostMapping("/del")
    public Result delete(@RequestParam Map<String,Object> map){
        Integer productId = MapUtils.getInteger(map,"productId");
        if(null != productId){
            int re = productSV.deleteByPrimaryKey(productId);
            return Result.success("构件删除成功",re);
        }
        return Result.failed("构件删除失败");
    }

}